import * as vscode from 'vscode';
import { handleError } from '../log';
import { UserFriendlyError } from '../errors/user_friendly_error';

// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
export async function jsonFormat() {
  const editor = vscode.window.activeTextEditor;

  if (editor) {
    const document = editor?.document
    const selection = editor?.selection
    const word = document?.getText(selection);
    if (word) {
      try {
        const jsonResult = JSON.parse(word)
        const strResult = JSON.stringify(jsonResult, null, '\t')
        await editor.edit(editBuilder => {
          editBuilder.replace(selection, strResult);
        });
      } catch (e) {
        handleError(
          new UserFriendlyError(
            'CSDN Workflow: 格式化失败，点击查看详情',
            e
          ),
        );
      }
    } else {
      await vscode.window.showInformationMessage('CSDN Workflow: 没有已经选中的 json 内容');
    }
  }else{
    await vscode.window.showInformationMessage('CSDN Workflow: 没有已经打开的文件');
  }
}
